package com.njxxted.activiti.common.util;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * 描述：根据文件名称判断类型
 * <p>
 * 作者：HuTongFu
 * 时间：2019/6/25 10:56
 */
public class FileType {

    public static String fileType(String fileName) {
        if (fileName == null) {
            return null;
        }
        // 获取文件后缀名并转化为写，用于后续比较
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

        // 创建图片类型数组0
        String[] img = {"bmp", "jpg", "jpeg", "png", "tiff", "gif", "pcx", "tga", "exif", "fpx", "svg", "psd",
                "cdr", "pcd", "dxf", "ufo", "eps", "ai", "raw", "wmf"};
        if (checkType(img, fileType)) {
            return "I";
        }

        // 创建文档类型数组1
        String[] document = {"txt", "doc", "docx", "xls", "xlsx", "htm", "html", "jsp", "rtf", "wpd", "pdf", "ppt"};
        if (checkType(document, fileType)) {
            return "D";
        }

        // 创建视频类型数组2
        String[] video = {"mp4", "avi", "mov", "wmv", "asf", "navi", "3gp", "mkv", "f4v", "rmvb", "webm"};
        if (checkType(video, fileType)) {
            return "V";
        }

        // 创建音乐类型数组3
        String[] music = {"mp3", "wma", "wav", "mod", "ra", "cd", "md", "asf", "aac", "vqf", "ape", "mid", "ogg",
                "m4a", "vqf"};
        if (checkType(music, fileType)) {
            return "M";
        }

        return "U";
    }

    private static boolean checkType(String[] arr, String fileType) {
        return Arrays.asList(arr).parallelStream().anyMatch(e -> e.equals(fileType));
    }

    /**
     * 下载文件名中含有中文的处理
     *
     * @param req
     * @param headName
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String encodeFileName(HttpServletRequest req, String headName) throws UnsupportedEncodingException {
        String filename;//IE9之前包括IE9都包含MSIE;IE10之后都包含Trident;edge浏览器包含Edge
        String userAgent = req.getHeader("User-Agent");
        if (userAgent.contains("MSIE") || userAgent.contains("Trident") || userAgent.contains("Edge")) {
            filename = URLEncoder.encode(headName, "UTF-8");
        } else {
            filename = new String(headName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        return filename;
    }

}